const express = require('express');
const multer = require('multer');
const axios = require('axios');
const { v4: uuidv4 } = require('uuid');

const router = express.Router();
// const mysqlConenct = require('../db/mysql');
// const Cat = require('../db/mongoDB/models/cats');
// const mongoConenct = require('../db/mongoDB');
const apiKey = '换成你自己的apiKey';
function initMulter() {
  const storage = multer.diskStorage({
    //确定图片存储的位置
    destination: function (req, file, cb) {
      cb(null, './public/uploadImgs');
    },
    //确定图片存储时的名字,注意，如果使用原名，可能会造成再次上传同一张图片的时候的冲突
    filename: function (req, file, cb) {
      let originalname = file.originalname;
      cb(null, uuidv4() + originalname.slice(originalname.lastIndexOf('.')));
      // cb(null, Date.now() + file.originalname);
    }
  });
  //生成的专门处理上传的一个工具，可以传入storage、limits等配置
  return multer({ storage });
}

const upload = initMulter();

router.get('/', (req, res) => {
  res.send('==server-home==');
});

router.get('/aiSearch', (req, res) => {
  const {content} = req.query
  const postData = {
    "model": "glm-4-plus",
    // "stream": true,

    "messages": [
        {
          "role": "user",
          "content": content
        }
    ]
  }
  axios.post('https://open.bigmodel.cn/api/paas/v4/chat/completions', postData, {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${apiKey}`
    }
  }).then(response => {
    console.log(JSON.stringify(response.data));
    // res.send(response.data.choices[0].message.content);
   
    res.status(200).json({
      code: '0000',
      data: response.data.choices[0]?.message
      // data: response.data.choices[0]?.message
    });
  });
 
});

// 测试文件上传
router.post('/upload', upload.single('file'), (req, res) => {
  let url = '/uploadImgs/' + req.file.filename;
  res.json({
    code: '0000',
    data: url
  });
});

// 测试连接mysql查询数据
// router.get('/stuList', (req, res) => {
//   const sql = 'select * from stus';
//   mysqlConenct.query(sql, (err, data) => {
//     if (err) {
//       console.log(err);
//       return;
//     }
//     res.send({
//       code: '0000',
//       data
//     });
//   });
//   // res.json(require('./mock/stuList.json'));
// });

// 测试连接mongodb查询数据
/* router.get('/addCat', (req, res) => {
  const miaomiao = new Cat({ name: 'miaomiao', age: 2 });

  // 插入一条数据
  miaomiao.save(function (err, fluffy) {
    if (err) return console.error(err);
    // miaomiao.speak();

    // 查找数据
    Cat.find(function (err, data) {
      if (err) return console.error(err);
      res.send(data);
    });
  });
}); */

module.exports = router;
